package myfirstproject.firstproject.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import myfirstproject.firstproject.Mapper.UserMapper;
import myfirstproject.firstproject.Service.IUserService;
import myfirstproject.firstproject.domain.DTO.UserDTO;
import myfirstproject.firstproject.domain.DTO.UserLoginDTO;
import myfirstproject.firstproject.domain.DTO.UserQueryDTO;
import myfirstproject.firstproject.domain.VO.UserVo;
import myfirstproject.firstproject.domain.po.User;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import myfirstproject.firstproject.result.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-09-16
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void saveUser(UserDTO userDTO) {
        User one = lambdaQuery()
                .eq(User::getUsername, userDTO.getUsername())
                .one();
        if(one != null){
            throw new RuntimeException("用户名已存在");
        }
        String phoneRegex = "^1[3-9]\\d{9}$";
        Pattern pattern1 = Pattern.compile(phoneRegex);
        if (userDTO.getPhone() == null || !pattern1.matcher(userDTO.getPhone()).matches()) {
            throw new RuntimeException("手机号不正确");
        }
        //检查邮箱格式(正则表达式)
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        Pattern pattern = Pattern.compile(emailRegex);
        Matcher matcher = pattern.matcher(userDTO.getEmail());
        if (!matcher.matches()) {
            throw new RuntimeException("邮箱格式不正确");
        }
        if (userDTO.getPassword().length() < 6 || userDTO.getPassword().length() > 12){
            throw new RuntimeException("密码必须在6~12位");
        }
        User user = BeanUtil.copyProperties(userDTO, User.class);
        user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        user.setCreateBy(userDTO.getUsername());
        user.setUpdateBy(userDTO.getUsername());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
    }

    @Override
    public boolean checkID(String username) {
        if(userMapper.checkID(username)==0){
            return false;
        }
        return true;
    }

    @Override
    public void updateUser(UserDTO userDTO) {
        String phoneRegex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(phoneRegex);
        if (userDTO.getPhone() == null || !pattern.matcher(userDTO.getPhone()).matches()) {
            throw new RuntimeException("手机号不正确");
        }
        if (userDTO.getPassword().length() < 6 || userDTO.getPassword().length() > 12){
            throw new RuntimeException("密码必须在6~12位");
        }
        User user = BeanUtil.copyProperties(userDTO, User.class);
        user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        user.setUpdateBy(userDTO.getUsername());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);


    }

    @Override
    public UserVo queryUserAndAddressById(String id) {
        User user = getById(id);
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user,userVo);
        return userVo;
    }

    @Override
    public PageResult<UserVo> queryUsersPage(UserQueryDTO query) {
        //1.构建查询条件
        String phone = query.getPhone();
        String nickname = query.getNickname();
        Integer age = query.getAge();
        String address = query.getAddress();
        Integer sex = query.getSex();
        Integer minAge = query.getMinAge();
        Integer maxAge = query.getMaxAge();
        //1.1 分页条件
        Page<User> page = Page.of(query.getPage(), query.getPageSize());
        //2.分页查询
        Page<User> p = lambdaQuery().like(nickname != null, User::getNickname, nickname)
                .like(phone != null, User::getPhone, phone)
                .like(address != null, User::getAddress, address)
                .between(age != null && minAge != null && maxAge != null, User::getAge, minAge, maxAge)
                .eq(sex != null, User::getSex, sex)
                .page(page);
        //3.封装VO结果
        PageResult<UserVo> dto = new PageResult<>();
        //总条数
        dto.setTotal(p.getTotal());
        //总页数
        dto.setPages(p.getPages());
        //当前页数据
        List<User> records = p.getRecords();
        if(CollUtil.isEmpty(records)){
            dto.setList(Collections.emptyList());
            return dto;
        }
        //3.4 拷贝user的vo
        List<UserVo> list = BeanUtil.copyToList(records, UserVo.class);
        dto.setList(list);
        //4.返回
        return dto;
    }

    @Override
    public User login(UserLoginDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        User user = lambdaQuery()
                .eq(User::getUsername, username)
                .eq(User::getPassword, DigestUtils.md5DigestAsHex(password.getBytes()))
                .one();
        if (user == null){
            throw new RuntimeException("用户名或密码错误");
        }


        return user;
    }
}
